import type { BrowserWindow, Cookie } from 'electron'
import type { Cookie as LocalCookie } from 'shared-types'

import { useController } from './controller'
import { useStore } from './store'

export async function initCookies(win: BrowserWindow) {
  try {
    await getCookies(win)
    startSetCookiesTimer(win)
  } catch (err) {
    console.error(err)
  }
}

async function clearSessionStorageData(win: BrowserWindow) {
  const store = useStore()
  const { role } = store.getUserInfo()
  const session = win.webContents.session
  // 子账号
  if (role !== 1) {
    // 清除缓存
    await session.clearStorageData()
  }
}

async function getCookies(win: BrowserWindow) {
  const controller = useController()
  const data = await controller.listCookies({ urls: [] })
  doUpdateSessionCookies(win, data.list)
}

function startSetCookiesTimer(win: BrowserWindow) {
  setInterval( async () => {
    await setCookies(win)
  }, 60000)
}

async function setCookies(win: BrowserWindow) {
  const store = useStore()
  const controller = useController()
  const cookies = win.webContents.session.cookies

  try {
    const query = await Promise.all(store.getPlatforms().map(async (platform) => {
      const filterCookies = await cookies.get({ url: platform.url })
      const content = platform.cookie_names.every(name => filterCookies.some(c => c.name === name)) ? JSON.stringify(filterCookies) : ''
      return { url: platform.url, content }
    }))
    const updateData = await controller.updateCookies({ list: query.filter(i => i.content !== '') })
    const urls = query.filter(i => i.content === '').map(i => i.url)
    if (urls.length > 0) {
      const data = await controller.listCookies({ urls })
      updateData.list = [...updateData.list, ...data.list]
    }
    doUpdateSessionCookies(win, updateData.list)
  } catch (err) {
    console.error(err)
  }
}
function doUpdateSessionCookies(win: BrowserWindow, cookies: LocalCookie[]) {
  if (cookies.length === 0) {
    return
  }

  cookies.forEach(item => {
    if (item.content) {
      const session = win.webContents.session
      const cookies = JSON.parse(item.content) as Cookie[]
      cookies.forEach(cookie => {
        session.cookies.set({ url: item.url, ...cookie })
      })
    }
  })
  // 刷新相关的 browserViews
  const views = win.getBrowserViews()
  views.forEach(view => {
    const viewUrl = view.webContents.getURL()
    if (cookies.some(cookie => viewUrl.startsWith(cookie.url))) {
      view.webContents.reload()
    }
  })
}
